package juc;

import java.util.concurrent.CountDownLatch;

/**
 * @author lzy
 * Create DateTime: 2018/7/17 10:11
 * @version v1.0
 * <p>
 * CountDownLaunch:闭锁，在完成某些运算时，只有其他线程的运算全部完成时，当前运算才继续执行
 */
public class TestCountDownLaunch {
    public static void main(String[] args) {
        final int threadNum = 5;
        final CountDownLatch latch = new CountDownLatch(threadNum);
        LatchDemo demo = new LatchDemo(latch);

        long start = System.currentTimeMillis();

        for (int i = 0; i < threadNum; i++) {
            new Thread(demo).start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("耗费时间为：" + (end - start));
    }
}

class LatchDemo implements Runnable {

    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                for (int i = 0; i < 5000; i++) {
                    if (i % 2 == 0) {
                        System.out.println(i);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    }
}
